package com.jfinal.cli.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.jfinal.cli.common.exception.BizException;

/**
 * 全局拦截器
 *
 * @author: lbq
 * @email: 526509994@qq.com
 * @date: 16/8/21
 */
public class GlobalActionInterceptor implements Interceptor {
    private final Log log = Log.getLog(this.getClass());

    @Override
    public void intercept(Invocation inv) {
        Controller c = inv.getController();
        try {
            inv.invoke();
        } catch (Exception e) {
            long code = -1;
            String message;
            String type;
            if (e.getClass() == BizException.class) {
                code = ((BizException) e).getCode();
                message = e.getMessage();
                type = "biz";
            } else {
                message = "计划外异常,请联系管理员:" + e.getMessage();
                type = "others";
            }

            e.printStackTrace();

            Ret ret = Ret.fail();
            ret.set("code", code);
            ret.set("message", message);
            ret.set("type", type);
            ret.set("timestamp", System.currentTimeMillis());

            c.renderJson(ret);
        }
    }
}
